#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_003.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_003.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test3.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nettle/sha.h>

int main() {
    // 初始化SHA-1上下文结构体
    struct sha1_ctx ctx;
    // 待哈希的文本
    const char *message = "The quick brown fox jumps over the lazy dog";
    // 预期的SHA-1哈希值对应的文本
    const char *expected_sha1_digest = "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12";
    // 存储计算得到的SHA-1哈希值
    uint8_t digest[SHA1_DIGEST_SIZE];
    // 临时变量用于打印结果
    char temp[3];

    // 初始化SHA-1上下文
    sha1_init(&ctx);
    // 进行哈希计算
    sha1_update(&ctx, strlen(message), (const uint8_t *)message);
    // 获取哈希结果
    sha1_digest(&ctx, sizeof(digest), digest);

    // 打印SHA-1哈希值（需转化为十六进制表示）
    printf("SHA-1哈希计算结果: ");
    for (size_t i = 0; i < sizeof(digest); i++) {
        printf("%02x", digest[i]);
    }
    printf("\\n");

    // 对比计算结果与预期结果
    for (size_t i = 0; i < sizeof(digest); ++i) {
        snprintf(temp, sizeof(temp), "%02x", digest[i]);
        if (strncmp(&expected_sha1_digest[i*2], temp, 2) != 0) {
            printf("哈希计算结果与预期不匹配。\\n");
            printf("位置 %lu: 预期 %c%c, 得到 %s\\n",
                   i, expected_sha1_digest[i*2], expected_sha1_digest[i*2 + 1], temp);
            return EXIT_FAILURE;
        }
    }

    // 如果所有哈希值相匹配
    printf("SHA-1哈希计算结果与预期匹配。\\n");

    return EXIT_SUCCESS;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test3 nettle_test3.c -lnettle')
        code, nettle_result = self.cmd("./nettle_test3")
        self.assertIn('SHA-1哈希计算结果与预期匹配。', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test3 nettle_test3.c')
